using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Silvery;
using System.IO;

using System.Windows.Media.Imaging;
using ICSharpCode.SharpZipLib.Zip;
using Silvery.Data;
namespace RoleEditer
{
    /// <summary>
    /// 保存的是NSpiritData
    /// 一个角色对应一个
    /// </summary>
    public sealed class SpiritManager:Dictionary<TreeViewItem,NSpiritData>
    {
        private SpiritManager()
        {
        }
        static SpiritManager _this;
        //单例
        public static SpiritManager Instance
        {
            get
            {
                if (_this == null)
                    _this = new SpiritManager();
                return _this;
            }
        }
        //通过动画名字（精灵文件）检测，是否已经存在
        public bool ContainsSpirit(string name)
        {
            foreach (var item in this.Keys)
            {
                if (((string)item.Header) == name)
                    return true;
            }
            return false;
        }
        //通过动画Item或者精灵Item取得精灵Item，主要用于TreeView.Selected的判定
        public TreeViewItem_Spirite GetSpiritItem(TreeViewItem saveitem)
        {
            TreeViewItem_Spirite Saveitem = null ;
            if (saveitem is TreeViewItem_Spirite)
                Saveitem = saveitem as TreeViewItem_Spirite;
            else
                if (saveitem is TreeViewItem_Animat)
                    Saveitem = (saveitem as TreeViewItem_Animat).ParentSpirit;
                else
                {
                    MessageBox.Show("保存目标不正确！");                   
                }
            return Saveitem;
        }
        //保存精灵文件
        public void SaveSpirit(TreeViewItem saveitem,Stream filestream)
        {
            if (saveitem == null)
            {
                MessageBox.Show("保存目标不正确！");
                return;
            }
            //这段代码和上面重复了
            TreeViewItem_Spirite Saveitem;
            if (saveitem is TreeViewItem_Spirite)
                Saveitem = saveitem as TreeViewItem_Spirite;
            else
                if (saveitem is TreeViewItem_Animat)
                    Saveitem = (saveitem as TreeViewItem_Animat).ParentSpirit;
                else
                {
                    MessageBox.Show("保存目标不正确！");
                    return;
                }

            var t = this[Saveitem];
            Saveitem.Spirtfile_Fames.SpiritData = t;
            MemoryStream ms_Spirtfile_Fames = new MemoryStream();
            Saveitem.Spirtfile_Fames.Save(ms_Spirtfile_Fames);

            try
            {
                ZipFile zip = new ZipFile(filestream);
                zip.BeginUpdate();

                ms_Spirtfile_Fames.Position = 0;
                zip.Add(new StaticDataSource(ms_Spirtfile_Fames), SpiritFile_Frames.FileName);

                ImageTools.IO.Png.PngEncoder png = new ImageTools.IO.Png.PngEncoder();

                int i = 0;
                foreach (var item in t.Values)
                {
                    foreach (var imgframe in item)
                    {
                        
                        MemoryStream ms_imgFrame = new MemoryStream();
                        WriteableBitmap wb = new WriteableBitmap(imgframe.Source as BitmapImage);
                        png.Encode(ImageTools.ImageExtensions.ToImage(wb), ms_imgFrame);

                        ms_imgFrame.Position = 0;
                        zip.Add(new StaticDataSource(ms_imgFrame), i + ".png");
                        i += 1;
                        
                        //ms_imgFrame.Close();
                    }

                }
                zip.CommitUpdate();
                zip.Close();
            }
            catch(Exception ex)
            {
                ex.ToString();
            }

            ms_Spirtfile_Fames.Close();
            MessageBox.Show("\"" + saveitem.Header.ToString() + "\"保存成功");
        }
        //读取精灵文件
        public TreeViewItem_Spirite LoadSpirit(ZipFile file,string name)
        {
            TreeViewItem_Spirite load = null;
            int frame_index =  file.FindEntry(SpiritFile_Frames.FileName, false);
            if ( frame_index < 0)
            {
                MessageBox.Show("文件包错误");
                return load;
            }
            load = new TreeViewItem_Spirite(name);
            load.Spirtfile_Fames.Load(file.GetInputStream(frame_index));
            var framenames = load.Spirtfile_Fames.FrameNames;
            NSpiritData nd = new NSpiritData();
            foreach (var item in framenames)
            {
                //if (item == SpiritFile_Frames.Millisecondconst)
                //    continue;
                if (load.Spirtfile_Fames.Attributes.ContainsKey(item))
                    continue;
                BitmapImage bitmap = new BitmapImage();
                var fileindex = file.FindEntry(item, false);
                bitmap.SetSource(file.GetInputStream(fileindex));
                Image img = new Image() { Source = bitmap };
                Point offsetpoint = new Point();
                var x = load.Spirtfile_Fames[item, SpiritFile_Frames.OffsetX];
                var y = load.Spirtfile_Fames[item, SpiritFile_Frames.OffsetY];
                offsetpoint.X = Convert.ToDouble(x);
                offsetpoint.Y = Convert.ToDouble(y);
                img.Tag = offsetpoint; 
                var aniname = load.Spirtfile_Fames[item,SpiritFile_Frames.AniName];
                
                nd.AddFrame(aniname, img);                
            }
            this.Add(load, nd);
            foreach (var item in nd.Keys)
            {
                TreeViewItem_Animat ani = new TreeViewItem_Animat(item);
                load.Items.Insert(load.Items.Count-1, ani);
            }
            return load;
        }
        //设置所有帧的偏移点
        public void SetAllFrame(TreeViewItem target, Point offset)
        {
            
            if (target is TreeViewItem_Spirite)
            {
                MessageBox.Show("只能针对一组动画有效");
            }
            else
            {
                TreeViewItem_Animat Saveitem = target as TreeViewItem_Animat;
                if (Saveitem != null)
                {
                    foreach (var item in SpiritManager.Instance[Saveitem.ParentSpirit][Saveitem.AnimatName])
                    {
                        item.Tag = offset;
                    }

                }
                
            }
        }
        public void Rename(TreeViewItem_Animat target, string newname)
        {            
            var spiritdata = this[target.ParentSpirit];
            var listtemp = spiritdata[target.AnimatName];
            spiritdata.Remove(target.AnimatName);
            spiritdata.Add(newname, listtemp);
            target.AnimatName = newname;
        }
    }
}
